# coding: utf-8
import os

from flask import Flask, send_from_directory, request, Response
from obs import ObsClient

FRONTEND_FOLDER = "frontend"  # 前端文件地址

BUCKET_NAME = os.environ.get("bucket_name")
REGION = os.environ.get("region")

app = Flask(__name__, static_url_path="/" + FRONTEND_FOLDER)


@app.route('/upload_file')
def send_frontend():
    return send_from_directory(FRONTEND_FOLDER, "index.html")


@app.route("/upload_file/signed_url", methods=['GET'])
def get_signed_url():
    try:
        upload_path = request.args.get("upload_path", "").replace("\\", "/").strip("/")
        filename = request.args.get("fileName", "")
        file_path = "%s/%s" % (upload_path, filename) if upload_path else filename
        end_point = "obs.%s.myhuaweicloud.com" % REGION
        ak = request.headers.get("X-CFF-Access-Key")
        sk = request.headers.get("X-CFF-Secret-Key")
        obs_client = ObsClient(access_key_id=ak, secret_access_key=sk, server=end_point)
        res = obs_client.createSignedUrl('PUT', BUCKET_NAME, file_path, expires=3600,
                                         headers={'Content-Type': 'application/octet-stream'})
        print(res.signedUrl)
        html = f'{res.signedUrl}'
        return Response(html)
    except Exception as e:
        message = "Error: %s" % str(e)
        return Response(message)


if __name__ == "__main__":
    app.run(port=8000)
